# -*- coding: UTF-8 -*-
import sys
from PySide6 import QtCore
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QHBoxLayout, 
                              QVBoxLayout, QPushButton, QStackedWidget, QLabel, 
                              QComboBox, QDialog, QMenu, QMessageBox, QLineEdit, QSpinBox, 
                              QCheckBox, QRadioButton, QTextEdit, QPlainTextEdit,QSizeGrip)
from PySide6.QtGui import QPixmap, QIcon, QAction, QImage, QPainter, QColor, QPen, QPainterPath, QCursor
from PySide6.QtCore import QBuffer, Qt, QTranslator, QSize, Qt, QPoint, QSettings
from Icon import icons
from Menu.help import HelpMenus
from Home.home import HomeWindow
from Deviceinfo.deviceinfo import DeviceInfoWindow
from Updatelog.updatelog import UpdatelogWindow
from Icon.icons import TUBIAO_windows
import jwt


class BaseWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent) 

# 在MainApp类之前添加新的导航栏容器类
class NavigationContainer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.main_app = parent
        self.mouse_inside = False  # 添加标记来跟踪鼠标是否容器内
        
    def enterEvent(self, event):
        """当鼠标进入导航栏时触发"""
        self.mouse_inside = True
        if not self.main_app.manual_expanded:
            self.main_app.nav_expanded = True
            self.main_app.update_nav_state()
        super().enterEvent(event)
        
    def leaveEvent(self, event):
        """当鼠标离开导航栏时触发"""
        self.mouse_inside = False
        if not self.main_app.manual_expanded:
            self.main_app.nav_expanded = False
            self.main_app.update_nav_state()
        super().leaveEvent(event)

class MainApp(BaseWindow):
    def __init__(self):
        super().__init__()
        
        # 添加 settings 初始化
        self.settings = QSettings('Netconf', 'Netconf.cloud')
        
        # 设置窗口属性
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)
        
        # 添加大小调整相关的属性
        self._edge_grip = None
        self._resize_area = 5  # 调整大小的区域宽度
        self._resizing = False
        self._resize_edge = None
        
        # 设置最小窗口大小
        self.setMinimumSize(800, 600)
        
        # 用于窗口拖动
        self._drag_pos = None
        
        # 添加导航栏宽度相关的属性定义
        self.nav_width_expanded = 120  # 展开时的宽度
        self.nav_width_collapsed = 50  # 收缩时的宽度
        self.nav_expanded = True  # 导航栏状态标志
        self.manual_expanded = False  # 新增：标记是否是手动展开的状态
        
        self.help_menus = HelpMenus(self)
        self.setWindowTitle("Netconf.cloud v2.0.3-专业版")
        self.setGeometry(0, 0, 1100, 790)

        # 设置窗口图标
        icon_data = bytes.fromhex(TUBIAO_windows)
        pixmap_windows = QPixmap()
        pixmap_windows.loadFromData(icon_data)
        self.setWindowIcon(QIcon(pixmap_windows))

        # 主窗口的中央小部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)

        # 主布局
        main_layout = QHBoxLayout(central_widget)

        # 页面堆栈，用于存放不同的页面
        self.stacked_widget = QStackedWidget()
        self.init_pages()

        # 创建导航栏容器
        nav_container = NavigationContainer(self)
        nav_layout = QVBoxLayout(nav_container)
        nav_layout.setAlignment(Qt.AlignTop)
        nav_layout.setSpacing(10)
        nav_layout.setContentsMargins(0, 10, 0, 0)
        
        # 创建一个水平布局来放置展开/收缩按钮
        toggle_btn_layout = QHBoxLayout()
        toggle_btn_layout.setAlignment(Qt.AlignLeft)  # 设置为左对齐
        toggle_btn_layout.setContentsMargins(10, 0, 0, 0)  # 设置左边距为10
        
        # 创建展开/收缩按钮
        self.toggle_nav_btn = QPushButton()
        self.toggle_nav_btn.setFixedSize(35, 35)
        self.toggle_nav_btn.setFlat(True)  # 设置按钮扁平化
        # 设置图标大小
        icon_size = QSize(25, 25) if self.nav_expanded else QSize(25, 25)
        self.toggle_nav_btn.setIconSize(icon_size)
        self.toggle_nav_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.TUBIAO_left)))))
        self.toggle_nav_btn.clicked.connect(self.toggle_navigation)
        self.toggle_nav_btn.setCursor(QtCore.Qt.PointingHandCursor)

        # 设置展开/收缩按钮的样式
        self.toggle_nav_btn.setStyleSheet("""
            QPushButton {
                background-color: transparent;  /* 设置背景透明 */
                border: none;  /* 移除边框 */
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);  /* 鼠标悬停时的背景色 */
                border-radius: 5px;  /* 圆角 */
            }
        """)

        # 将按钮添加到水平布局中
        toggle_btn_layout.addWidget(self.toggle_nav_btn)

        # 将水平布局添加到导栏布局中
        nav_layout.addLayout(toggle_btn_layout)

        # 添加一些间距
        nav_layout.addSpacing(10)

        # 修改现有按钮的创建和连接方式
        self.btn_home = self.create_nav_button("首页", icons.TUBIAO_home, 0)
        self.btn_deviceinfo = self.create_nav_button("设备信息", icons.TUBIAO_device, 1)

        # 添加按钮点击事件连接
        self.btn_home.clicked.connect(lambda: self.highlight_button(self.btn_home, 0))
        self.btn_deviceinfo.clicked.connect(lambda: self.highlight_button(self.btn_deviceinfo, 1))

        # 添加按钮到导航栏布局
        nav_layout.addWidget(self.btn_home)
        nav_layout.addWidget(self.btn_deviceinfo)

        # 设置初始高亮状态
        self.highlight_button(self.btn_home, 0)  # 默认显示首页

        self.btn_update = QPushButton()
        self.btn_update.setFixedSize(35, 35)  # 设置按钮大小
        self.btn_update.setFlat(True)  # 去除按钮边框样式
        self.btn_update.setIcon(
            QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.TUBIAO_update)))))
        self.btn_update.setCursor(QtCore.Qt.PointingHandCursor)  # 设置鼠标悬停为手型
        self.btn_update.setToolTip("更新日志")  # 鼠标悬停时显示文字
        self.btn_update.clicked.connect(lambda: self.highlight_button(self.btn_update, 2))


        # 设置按钮图标的大小
        icon_size = QSize(25, 25)  # 调整为适当的尺寸
        self.btn_update.setIconSize(icon_size)

        # 创建一个垂直布局来垂直居中显示按钮和版本号，并靠底部对齐
        bottom_layout = QVBoxLayout()
        bottom_layout.addWidget(self.btn_update, alignment=Qt.AlignCenter)  # 居中显示按钮
        bottom_layout.addStretch(1)  # 容

        # 将垂直布局添加到导航栏布局的最下方
        nav_layout.addStretch(1)  # 将内容推到窗口底部
        nav_layout.addLayout(bottom_layout)
        nav_layout.addStretch(1)  # 确保内容在窗口底部对齐

        # 将导航栏容器添加到主布局
        main_layout.addWidget(nav_container)

        # 将页面堆栈添加到主布局的右侧
        main_layout.addWidget(self.stacked_widget)

        # 初始化翻页器
        self.translator = QTranslator()
        self.change_language("en")  # 默认语言为中文

        # 创建标题栏
        self.create_title_bar()
        
        # 主布局修改为垂直布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_vertical_layout = QVBoxLayout(central_widget)
        main_vertical_layout.setContentsMargins(0, 0, 0, 0)
        main_vertical_layout.setSpacing(0)
        
        # 添加标题栏
        main_vertical_layout.addWidget(self.title_bar)
        
        # 内容区域水平布局
        content_widget = QWidget()
        content_layout = QHBoxLayout(content_widget)
        content_layout.setContentsMargins(10, 0, 10, 10)
        main_vertical_layout.addWidget(content_widget)
        
        # 将导航栏和栈窗口添加到内容布局
        content_layout.addWidget(nav_container)
        content_layout.addWidget(self.stacked_widget)

        # 创建个人中心菜单
        self.user_menu = QMenu(self)
        self.login_action = QAction("登录", self)
        self.logout_action = QAction("退出登录", self)
        
        # 设置动作
        self.login_action.triggered.connect(self.show_login_dialog)
        self.logout_action.triggered.connect(self.logout)
        
        # 初始只添加登录选项
        self.user_menu.addAction(self.login_action)
        
        # 初始化时更新菜单状态
        self.update_menu_state()

    def init_pages(self):
        # 初始化并添加所有页面，传入 self 作为父窗口
        self.pages = [
            HomeWindow(self),
            DeviceInfoWindow(self),  # 传入 self 作为父窗口
            UpdatelogWindow(self)
        ]

        for page in self.pages:
            self.stacked_widget.addWidget(page)

    def create_nav_button(self, text, icon_hex, index):
        """创建导航按钮的通用方法"""
        button = QPushButton(text)
        button.setFixedSize(self.nav_width_expanded, 30)
        button.setFlat(True)
        button.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icon_hex)))))
        button.setCursor(QtCore.Qt.PointingHandCursor)
        
        # 设置工具提示
        button.setToolTip(text.strip())
        
        # 简化按钮样式
        button.setStyleSheet("""
            QPushButton {
                text-align: left;
                padding-left: 5px;
                background-color: transparent;
                border: none;
                border-radius: 5px;
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);
            }
            QPushButton:pressed {
                color: red;
            }
        """)
        
        return button

    def toggle_navigation(self):
        """切换导航栏的展开/收缩状态"""
        # 如果当前是收缩状态，则展开
        if not self.nav_expanded:
            self.nav_expanded = True
            self.manual_expanded = True
        # 如果当前是展开状态，则收缩
        else:
            self.nav_expanded = False
            self.manual_expanded = False
        
        # 更新展开/收缩按钮的图标
        icon_hex = icons.TUBIAO_right if self.nav_expanded else icons.TUBIAO_left
        self.toggle_nav_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icon_hex)))))
        
        self.update_nav_state()

    def update_nav_state(self):
        """更新导航栏的展开/收缩状态"""
        nav_width = self.nav_width_expanded if self.nav_expanded else self.nav_width_collapsed
        
        # 更新所有导航按钮的状态
        for button in [self.btn_home, self.btn_deviceinfo, self.btn_update]:
            button.setFixedSize(nav_width, 30)
            
            # 检查是否是当前高亮的按钮
            is_highlighted = hasattr(self, '_current_highlighted_button') and button == self._current_highlighted_button
            
            if self.nav_expanded:
                button.setText(button.property("full_text") or button.toolTip())
                # 展开状态的样式
                if is_highlighted:
                    button.setStyleSheet("""
                        QPushButton {
                            text-align: left;
                            padding-left: 5px;
                            color: #FF0000;
                            background-color: #FFC8C8;
                            border: none;
                        }
                        QPushButton:hover {
                            background-color: #FFB0B0;
                        }
                    """)
                else:
                    button.setStyleSheet("""
                        QPushButton {
                            text-align: left;
                            padding-left: 5px;
                            background-color: transparent;
                            border: none;
                        }
                        QPushButton:hover {
                            background-color: rgba(0, 0, 0, 0.1);
                        }
                    """)
            else:
                if not button.property("full_text"):
                    button.setProperty("full_text", button.text())
                button.setText("")
                # 收缩状态的样式
                if is_highlighted:
                    button.setStyleSheet("""
                        QPushButton {
                            background-color: #FFC8C8;
                            border: none;
                            padding: 5px;
                        }
                        QPushButton:hover {
                            background-color: #FFB0B0;
                        }
                    """)
                else:
                    button.setStyleSheet("""
                        QPushButton {
                            background-color: transparent;
                            border: none;
                            padding: 5px;
                        }
                        QPushButton:hover {
                            background-color: rgba(0, 0, 0, 0.1);
                        }
                    """)
            
            # 调整图标大小
            icon_size = QSize(20, 20) if self.nav_expanded else QSize(25, 25)
            button.setIconSize(icon_size)

    def highlight_button(self, button, index):
        """高亮显示选中的按钮"""
        # 重置所有按钮样式
        for btn in [self.btn_home, self.btn_deviceinfo]:
            btn.setStyleSheet("""
                QPushButton {
                    text-align: left;
                    padding-left: 5px;
                    background-color: transparent;
                    border: none;
                }
                QPushButton:hover {
                    background-color: rgba(0, 0, 0, 0.1);
                }
            """)

        # 设置当前按钮样式
        self.stacked_widget.setCurrentIndex(index)
        
        # 根据导航栏状态设置不同的样式
        if self.nav_expanded:
            button.setStyleSheet("""
                QPushButton {
                    text-align: left;
                    padding-left: 5px;
                    color: #FF0000;
                    background-color: #FFC8C8;
                    border: none;
                }
                QPushButton:hover {
                    background-color: #FFB0B0;
                }
            """)
        else:
            button.setStyleSheet("""
                QPushButton {
                    background-color: #FFC8C8;
                    border: none;
                    padding: 5px;
                }
                QPushButton:hover {
                    background-color: #FFB0B0;
                }
            """)
        
        # 保存当前选中的按钮
        self._current_highlighted_button = button
    

    def change_language(self, language):
        if language == "zh":
            self.translator.load("translations_zh.qm")
        elif language == "en":
            self.translator.load("translations_en.qm")
        else:
            return
        QApplication.instance().installTranslator(self.translator)
        self.setWindowTitle(self.tr("Netconf.cloud v2.0.3-专业版"))
        self.btn_home.setText(self.tr("   首页       "))
        self.btn_deviceinfo.setText(self.tr("   设备信息"))

    def create_title_bar(self):
        """创建标题栏"""
        self.title_bar = QWidget()
        self.title_bar.setFixedHeight(40)
        title_layout = QHBoxLayout(self.title_bar)
        title_layout.setContentsMargins(10, 0, 10, 0)
        
        # 添加图标
        icon_label = QLabel()
        icon_pixmap = QPixmap()
        icon_pixmap.loadFromData(bytes.fromhex(TUBIAO_windows))
        icon_label.setPixmap(icon_pixmap.scaled(25, 25, Qt.KeepAspectRatio, Qt.SmoothTransformation))
        title_layout.addWidget(icon_label)
        
        # 添加标题
        self.title_label = QLabel("Netconf.cloud v2.0.3-专业版")  # 将标题标签保存为类属性
        title_layout.addWidget(self.title_label)
        title_layout.addStretch()
        
        # 统一按钮样式
        button_style = """
            QPushButton {
                background-color: transparent;
                border: none;
                border-radius: 15px;
                padding: 5px;
            }
            QPushButton:hover {
                background-color: rgba(0, 0, 0, 0.1);
            }
            QPushButton#closeButton:hover {
                background-color: #FF0000;
            }
            QPushButton#closeButton:hover QIcon {
                color: white;
            }
        """
        
        # 个人中心按钮
        self.user_button = QPushButton()
        self.user_button.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.login)))))
        self.user_button.setFixedSize(30, 30)
        self.user_button.setFlat(True)
        self.user_button.setStyleSheet(button_style)
        self.user_button.setToolTip("个人中心")
        self.user_button.clicked.connect(self.show_user_menu)
        
        # 添加帮助按钮
        help_btn = QPushButton()
        help_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.help)))))
        help_btn.setFixedSize(30, 30)
        help_btn.setFlat(True)
        help_btn.setStyleSheet(button_style)
        help_btn.setToolTip("帮助")
        help_btn.clicked.connect(self.show_help_menu)
        
        # 添加窗口控制按钮
        min_btn = QPushButton()
        min_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.minButton)))))
        min_btn.setIconSize(QSize(16, 16))
        min_btn.setObjectName("minButton")

        max_btn = QPushButton()
        max_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.maxButton)))))
        max_btn.setIconSize(QSize(16, 16))
        max_btn.setObjectName("maxButton")

        close_btn = QPushButton()
        close_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.closeButton)))))
        close_btn.setIconSize(QSize(16, 16))
        close_btn.setObjectName("closeButton")

        for btn in (min_btn, max_btn, close_btn):
            btn.setFixedSize(30, 30)
            btn.setFlat(True)
            btn.setStyleSheet(button_style)
        
        min_btn.clicked.connect(self.showMinimized)
        max_btn.clicked.connect(self.toggle_maximize)
        close_btn.clicked.connect(self.close)
        
        # 修改添加到布局的顺序
        title_layout.addWidget(self.user_button)
        title_layout.addWidget(help_btn)
        title_layout.addWidget(min_btn)
        title_layout.addWidget(max_btn)
        title_layout.addWidget(close_btn)

    def show_help_menu(self):
        """显示帮助菜单"""
        menu = QMenu(self)
        menu.setStyleSheet("""
            QMenu {
                background-color: white;
                border: 1px solid #cccccc;
                border-radius: 5px;
                padding: 5px;
            }
            QMenu::item {
                padding: 5px 30px 5px 30px;
                border-radius: 3px;
            }
            QMenu::item:selected {
                background-color: #e6e6e6;
            }
        """)
        
        # 修改这一行，添加 auto_check=False 参数
        menu_items = [
            ("关于软件", lambda: self.help_menus.show_about_dialog()),
            ("免责声明", lambda: self.help_menus.show_disclaimer()),
        ]
        
        # 添加菜单项
        for text, callback in menu_items:
            action = menu.addAction(text)
            action.triggered.connect(callback)
        
        # 使用按钮的位置显示菜单
        button_pos = self.sender().mapToGlobal(self.sender().rect().bottomLeft())
        menu.exec(button_pos)

    def toggle_maximize(self):
        """切换最大化/还原窗口状态"""
        max_btn = self.findChild(QPushButton, "maxButton")
        if max_btn:
            if self.isMaximized():
                self.showNormal()
                max_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.maxButton)))))#最大化
            else:
                self.showMaximized()
                max_btn.setIcon(QIcon(QPixmap.fromImage(QImage.fromData(bytes.fromhex(icons.minButton)))))

    def isInResizeArea(self, pos):
        """检查鼠标是否在窗口边缘的调整区域内"""
        rect = self.rect()
        return (
            pos.x() <= self._resize_area or  # 左边
            pos.x() >= rect.right() - self._resize_area or  # 右边
            pos.y() >= rect.bottom() - self._resize_area or  # 下边
            pos.y() <= self._resize_area  # 上边
        )

    def getResizeEdge(self, pos):
        """获取调整大小的边缘"""
        rect = self.rect()
        if pos.x() <= self._resize_area:
            if pos.y() <= self._resize_area:
                return 'top-left'
            elif pos.y() >= rect.bottom() - self._resize_area:
                return 'bottom-left'
            return 'left'
        elif pos.x() >= rect.right() - self._resize_area:
            if pos.y() <= self._resize_area:
                return 'top-right'
            elif pos.y() >= rect.bottom() - self._resize_area:
                return 'bottom-right'
            return 'right'
        elif pos.y() <= self._resize_area:
            return 'top'
        elif pos.y() >= rect.bottom() - self._resize_area:
            return 'bottom'
        return None

    def mousePressEvent(self, event):
        """鼠标按下事件"""
        if event.button() == Qt.LeftButton:
            if event.pos().y() <= self.title_bar.height():
                self._drag_pos = event.globalPos() - self.pos()
                event.accept()
            else:
                edge = self.getResizeEdge(event.pos())
                if edge:
                    self._resizing = True
                    self._resize_edge = edge
                    self._drag_pos = event.globalPos()
                    event.accept()
                else:
                    self._drag_pos = None

    def mouseMoveEvent(self, event):
        """鼠标移动事件"""
        if not self._resizing and not self._drag_pos:
            # 更新鼠标样式
            edge = self.getResizeEdge(event.pos())
            if edge:
                if edge in ['left', 'right']:
                    self.setCursor(Qt.SizeHorCursor)
                elif edge in ['top', 'bottom']:
                    self.setCursor(Qt.SizeVerCursor)
                elif edge in ['top-left', 'bottom-right']:
                    self.setCursor(Qt.SizeFDiagCursor)
                elif edge in ['top-right', 'bottom-left']:
                    self.setCursor(Qt.SizeBDiagCursor)
            else:
                self.setCursor(Qt.ArrowCursor)
        
        if event.buttons() == Qt.LeftButton:
            if self._resizing and self._resize_edge:
                # 处理调整大小
                diff = event.globalPos() - self._drag_pos
                new_geometry = self.geometry()
                
                if self._resize_edge in ['left', 'top-left', 'bottom-left']:
                    new_geometry.setLeft(new_geometry.left() + diff.x())
                if self._resize_edge in ['right', 'top-right', 'bottom-right']:
                    new_geometry.setRight(new_geometry.right() + diff.x())
                if self._resize_edge in ['top', 'top-left', 'top-right']:
                    new_geometry.setTop(new_geometry.top() + diff.y())
                if self._resize_edge in ['bottom', 'bottom-left', 'bottom-right']:
                    new_geometry.setBottom(new_geometry.bottom() + diff.y())
                
                # 确保不小于最小尺寸
                if new_geometry.width() >= self.minimumWidth() and new_geometry.height() >= self.minimumHeight():
                    self.setGeometry(new_geometry)
                    self._drag_pos = event.globalPos()
            
            elif self._drag_pos is not None:
                # 处理窗口拖动
                new_pos = event.globalPos() - self._drag_pos
                screen = QApplication.primaryScreen()
                screen_geometry = screen.availableGeometry()
                
                new_pos.setX(max(screen_geometry.left() - self.width() + 100, 
                               min(new_pos.x(), screen_geometry.right() - 100)))
                new_pos.setY(max(screen_geometry.top(), 
                               min(new_pos.y(), screen_geometry.bottom() - 50)))
                
                self.move(new_pos)
            event.accept()

    def mouseReleaseEvent(self, event):
        """鼠标释放事件"""
        self._drag_pos = None
        self._resizing = False
        self._resize_edge = None
        event.accept()

    def paintEvent(self, event):
        """绘制窗口"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)
        
        # 创建圆角路径
        path = QPainterPath()
        path.addRoundedRect(self.rect(), 10, 10)
        
        # 设置窗口背景
        painter.fillPath(path, QColor("#F0F3F6"))
        
        # 绘制边框
        painter.setPen(QPen(QColor(0, 0, 0, 30), 1))
        painter.drawPath(path)

    def show_user_menu(self):
        """显示用户菜单"""
        from User.user_center import UserCenter
        
        if not hasattr(self, 'user_center'):
            self.user_center = UserCenter(self)
        
        # 获取按钮位置
        button_pos = self.sender().mapToGlobal(self.sender().rect().bottomLeft())
        
        # 显示用户中心
        self.user_center.move(button_pos)
        self.user_center.show()

    def update_menu_state(self):
        """更新菜单状态"""
        # 清除所有现有的动作
        self.user_menu.clear()
        
        token = self.settings.value('user_token')
        is_logged_in = bool(token)
        
        if token:
            try:
                user_info = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
                
                # 已登录状态：只添加退出登录选项
                self.user_menu.addAction(self.logout_action)
                
            except (jwt.ExpiredSignatureError, jwt.InvalidTokenError):
                is_logged_in = False
                # Token无效，显示登录选项
                self.user_menu.addAction(self.login_action)
        else:
            # 未登录状态：只显示登录选项
            self.user_menu.addAction(self.login_action)
        
        # 更新用户名显示
        if hasattr(self, 'user_button'):
            if is_logged_in:
                try:
                    user_info = jwt.decode(token, 'your-secret-key', algorithms=['HS256'])
                except:
                    self.user_button.setText("个人中心")
            else:
                self.user_button.setText("")
    
    def show_login_dialog(self):
        """显示登录对话框"""
        dialog = LoginDialog(self)
        if dialog.exec() == QDialog.Accepted:
            self.update_menu_state()  # 登录成功后更新菜单状态
    
    def logout(self):
        """退出登录"""
        self.settings.remove('user_token')
        self.update_menu_state()  # 退出登录后更新菜单状态
        QMessageBox.information(self, "提示", "已退出登录")
    
    def resizeEvent(self, event):
        super().resizeEvent(event)
        # 确保 stacked_widget 中的当前窗口能够调整大小
        if hasattr(self, 'stacked_widget'):
            current_widget = self.stacked_widget.currentWidget()
            if current_widget:
                current_widget.setGeometry(self.stacked_widget.rect())

# 离线版本的主函数
def create_main_window():
    window = MainApp()
    primary_screen = QApplication.primaryScreen()
    screen_geometry = primary_screen.availableGeometry()
    window.setGeometry(
        screen_geometry.width() // 2 - window.width() // 2,
        screen_geometry.height() // 2 - window.height() // 2,
        window.width(),
        window.height(),
    )
    return window  # 只返回窗口，不执行应用主循环
